package com.inspector.app.ui.task

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.inspector.app.databinding.TaskItemBinding
import com.inspector.app.ui.task.TaskAdapter.ViewHolder
import com.inspector.app.ui.vo.TaskClickType
import com.inspector.app.ui.vo.TaskItem

class TaskAdapter(
    private val systemTask : Boolean, //[系统任务]
    private val listener: (TaskClickType, TaskItem) -> Unit
) : ListAdapter<TaskItem, ViewHolder>(itemCallback) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder.create(parent, listener)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        getItem(position).also {
            holder.bind(it, systemTask)
        }
    }


    class ViewHolder(
        private val itemBinding: TaskItemBinding,
        private val listener: (TaskClickType, TaskItem) -> Unit,
    ) : RecyclerView.ViewHolder(itemBinding.root) {
        fun bind(item: TaskItem, systemTask: Boolean) {
            itemBinding.item = item
            itemBinding.listener = listener
            itemBinding.systemTask = systemTask
            itemBinding.executePendingBindings()
        }

        companion object {
            fun create(parent: ViewGroup, listener: (TaskClickType, TaskItem) -> Unit): ViewHolder {
                val itemBinding =
                    TaskItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
                return ViewHolder(itemBinding, listener)
            }
        }
    }

    companion object {
        val itemCallback = object : DiffUtil.ItemCallback<TaskItem>() {
            override fun areItemsTheSame(oldItem: TaskItem, newItem: TaskItem): Boolean {
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(oldItem: TaskItem, newItem: TaskItem): Boolean {
                return oldItem == newItem
            }
        }
    }


}